package com.yaser.beans;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.TreeNode;
import org.primefaces.model.UploadedFile;
import org.primefaces.model.chart.PieChartModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.yaser.alfresco.AlfrescoWebScripts;
import com.yaser.alfresco.model.AlfrescoFolder;
import com.yaser.alfresco.model.FileList;
import com.yaser.framework.MyTreeNode;
import com.yaser.util.AlfrescoUtil;
import com.yaser.util.Messenger;

@Component
@Scope("view")
@Qualifier("homeBean")
public class HomeBean {

	@Autowired
	private AlfrescoWebScripts webscripts;

	@Autowired
	private Messenger messenger;

	@Autowired
	private LoginBean loginBean;

	private String folderName;

	private FileList selectedFile;

	private FileList tableRoot;

	private List<FileList> childFolders;

	private TreeNode treeRoot;

	private FileList selectedRoot;

	private TreeNode selectedNode;

	private String searchName;

	private FileList[] selectedFiles;

	private List<FileList> searchedFiles;

	private UploadedFile uploadedFile;

	private PieChartModel pieModel;
	
	
	@PostConstruct
	public void init() {
		tableRoot = new FileList();
		tableRoot.setNodeRef(loginBean.getUser().getBaseFolderNodeRef());
		treeRoot = new MyTreeNode("Root", null);
		loadDeafultTree();
		createChartModel();
	}

	private void createChartModel() {
		pieModel = new PieChartModel();  
		  
        pieModel.set("Free Space", 540);  
        pieModel.set("Used Space", 160);  
	}

	private void loadDeafultTree() {
		List<FileList> list;
		if (getTableRoot() == null) {
			list = webscripts.listChildrens(loginBean.getUser().getAlf_ticket(), loginBean.getUser().getBaseFolderNodeRef());
		} else {
			list = webscripts.listChildrens(loginBean.getUser().getAlf_ticket(), tableRoot.getNodeRef());
		}

		if (list != null) {
			for (FileList fileList : list) {
				if (fileList.isContainer()) {
					MyTreeNode node = new MyTreeNode(fileList, treeRoot);
					// new MyTreeNode(fileList, node);
					node.setLeaf(false);
				}
			}
		}
	}

	public void onNodeSelected(NodeSelectEvent event) {
		FileList f = new FileList();
		f.setName("Testg");
		TreeNode node = new MyTreeNode(f, event.getTreeNode());
		event.getTreeNode().addChild(node);
		event.getTreeNode().setExpanded(true);
	}
	

	public void onNodeExpanded(NodeExpandEvent event) {
		FileList file = (FileList) event.getTreeNode().getData();
		List<FileList> childrens = webscripts.listChildrens(loginBean.getUser().getAlf_ticket(), file.getNodeRef());
		event.getTreeNode().getChildren().clear();
		for (FileList fileList : childrens) {
			TreeNode node = new MyTreeNode(fileList, event.getTreeNode());
			event.getTreeNode().addChild(node);
			event.getTreeNode().setExpanded(true);
		}

		if (childrens == null || childrens.size() == 0) {
			MyTreeNode node = (MyTreeNode) event.getTreeNode();
			node.setLeaf(false);
		}
		
		
//		event.getTreeNode().setExpanded(true);

		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Expanded", event.getTreeNode().toString());
		FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public boolean deleteSelectedFiles() {

		for (FileList file : getSelectedFiles()) {
			String deleteResponse = webscripts.deleteNode(file.getNodeRef(), loginBean.getUser().getAlf_ticket());
			System.out.println("---------- delete response = "+deleteResponse);
		}

		return true;
	}

	public void listHomeFolder() {
		if (getTableRoot() == null) {
			setChildFolders(webscripts.listChildrens(loginBean.getUser().getAlf_ticket(), loginBean.getUser().getBaseFolderNodeRef()));
		} else {
			setChildFolders(webscripts.listChildrens(loginBean.getUser().getAlf_ticket(), tableRoot.getNodeRef()));
			System.out.println(childFolders);
		}
	}

	public String createNewFolder() {

		AlfrescoFolder afolder = webscripts.createFolder(loginBean.getUser().getAlf_ticket(), AlfrescoUtil.BASE_URL, tableRoot.getNodeRef(), folderName, null);
		if (afolder != null)
			messenger.facesErrorMsg("Uyar� ", folderName + " created");
		else
			messenger.facesErrorMsg("Uyar� ", folderName + " not created");

		folderName = "";

		return null;
	}

	public boolean deleteFile() {
		String deleteResponse = webscripts.deleteNode(selectedFile.getNodeRef(), loginBean.getUser().getAlf_ticket());
		System.out.println("Delete response = " + deleteResponse);
		return false;
	}

	public boolean copyTo() {
		if (selectedFile != null && selectedNode != null) {
			FileList destination = (FileList) selectedNode.getData();
			String result = webscripts.copy(selectedFile.getNodeRef(), destination.getNodeRef(), loginBean.getUser().getAlf_ticket());
			if ("Error".equals(result))
				return false;
			messenger.facesErrorMsg("File copied");
			return true;
		} else {
			messenger.facesErrorMsg("File copy error");
			return false;
		}
	}

	public boolean moveTo() {
		if (selectedFile != null && selectedNode != null) {
			FileList destination = (FileList) selectedNode.getData();
			String result = webscripts.move(selectedFile.getNodeRef(), destination.getNodeRef(), loginBean.getUser().getAlf_ticket());
			if ("Error".equals(result))
				return false;
			messenger.facesErrorMsg("File moved");
			return true;
		} else {
			messenger.facesErrorMsg("File move error");
			return false;
		}
	}

	public void handleFileUpload(FileUploadEvent event) throws IOException {

		String fileName = event.getFile().getFileName().substring(0, event.getFile().getFileName().lastIndexOf("."));

		String suffix = event.getFile().getFileName().substring(event.getFile().getFileName().lastIndexOf("."));

		File file = createFile(event.getFile(), fileName, suffix);

		String fileUpload = webscripts.fileUpload(loginBean.getUser().getAlf_ticket(), tableRoot.getNodeRef(), file);
		if (fileUpload != null) {
			FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		file.delete();
		// TODO uploaded file da silinmeli
	}

	private File createFile(UploadedFile uploadedFile, String fileName, String suffix) throws IOException {
		// File f = File.createTempFile(fileName, suffix);
		//
		//
		// InputStream inputstream = uploadedFile.getInputstream();
		//
		// OutputStream out = new FileOutputStream(f);
		// // byte buf[] = new byte[1024];
		//
		// out.write(uploadedFile.getContents());
		// //
		// // int len;
		// // while ((len = inputstream.read(buf)) > 0)
		// // out.write(buf, 0, len);
		// // out.close();
		// inputstream.close();

		ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
		File result = new File(extContext.getRealPath("//WEB-INF//" + uploadedFile.getFileName()));
		// System.out.println(extContext.getRealPath("//WEB-INF//files//" +
		// event.getFile().getFileName()));
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(result);
			byte[] buffer = new byte[6124];
			int bulk;
			InputStream inputStream = uploadedFile.getInputstream();
			while (true) {
				bulk = inputStream.read(buffer);
				if (bulk < 0) {
					break;
				}
				fileOutputStream.write(buffer, 0, bulk);
				fileOutputStream.flush();
			}
			fileOutputStream.close();
			inputStream.close();

		} catch (IOException e) {
			e.printStackTrace();
			FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The files were not uploaded!", "");
			FacesContext.getCurrentInstance().addMessage(null, error);
		}

		return result;
	}

	public void simpleUpload() throws IOException {
		String fileName = getUploadedFile().getFileName().substring(0, getUploadedFile().getFileName().lastIndexOf("."));

		String suffix = getUploadedFile().getFileName().substring(getUploadedFile().getFileName().lastIndexOf("."));

		File file = createFile(getUploadedFile(), fileName, suffix);

		String fileUpload = webscripts.fileUpload(loginBean.getUser().getAlf_ticket(), tableRoot.getNodeRef(), file);
		if (fileUpload != null) {
			FacesMessage msg = new FacesMessage("Succesful", getUploadedFile().getFileName() + " is uploaded.");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		file.delete();
		setUploadedFile(null);
	}
	
	public void downloadFile() {
		webscripts.redirecToDownloadURL(getSelectedFile());
	}

	
	public void searchFiles() {
		setSearchedFiles(webscripts.searchFilesByName(loginBean.getUser().getBaseFolderNodeRef(), getSearchName(), loginBean.getUser().getAlf_ticket()));
	}

	public AlfrescoWebScripts getWebscripts() {
		return webscripts;
	}

	public void setWebscripts(AlfrescoWebScripts webscripts) {
		this.webscripts = webscripts;
	}

	public String getFolderName() {
		return folderName;
	}

	public void setFolderName(String folderName) {
		this.folderName = folderName;
	}

	public void setChildFolders(List<FileList> childFolders) {
		this.childFolders = childFolders;
	}

	public List<FileList> getChildFolders() {
		listHomeFolder();
		return childFolders;
	}

	public void setSelectedFile(FileList selectedFile) {
		this.selectedFile = selectedFile;
	}

	public FileList getSelectedFile() {
		return selectedFile;
	}

	public void setTableRoot(FileList tableRoot) {
		this.tableRoot = tableRoot;
	}

	public FileList getTableRoot() {
		return tableRoot;
	}

	public void setTreeRoot(TreeNode treeRoot) {
		this.treeRoot = treeRoot;
	}

	public TreeNode getTreeRoot() {
		return treeRoot;
	}

	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = selectedNode;
	}

	public TreeNode getSelectedNode() {
		return selectedNode;
	}

	public void setSelectedRoot(FileList selectedRoot) {
		this.selectedRoot = selectedRoot;
		tableRoot = webscripts.findNode(loginBean.getUser().getAlf_ticket(), selectedRoot.getParentNodeRef());
		if (tableRoot.getNodeRef().contains(loginBean.getUser().getBaseFolderNodeRef()))
			tableRoot.setParentNodeRef(null);
	}

	public FileList getSelectedRoot() {
		return selectedRoot;
	}

	public void setSearchName(String searchName) {
		this.searchName = searchName;
	}

	public String getSearchName() {
		return searchName;
	}

	public void setSearchedFiles(List<FileList> searchedFiles) {
		this.searchedFiles = searchedFiles;
	}

	public List<FileList> getSearchedFiles() {
		return searchedFiles;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setPieModel(PieChartModel pieModel) {
		this.pieModel = pieModel;
	}

	public PieChartModel getPieModel() {
		return pieModel;
	}

	public void setSelectedFiles(FileList[] selectedFiles) {
		this.selectedFiles = selectedFiles;
	}

	public FileList[] getSelectedFiles() {
		return selectedFiles;
	}
}
